package validator.handle;

import java.lang.annotation.Annotation;
import java.util.ArrayList;

import validator.annotation.Range;
import validator.exception.ValidateException;

public class RangeValidator implements Validator {

	private ArrayList<Class<?>> types = new ArrayList<Class<?>>();

	public RangeValidator() {
		types.add(int.class);
		types.add(double.class);
		types.add(long.class);
		types.add(float.class);
		types.add(Integer.class);
		types.add(Long.class);
		types.add(Double.class);
		types.add(Float.class);
		types.add(String.class);
	}

	@Override
	public boolean isValid(Class<?> clazz) {
		return types.contains(clazz);
	}

	@Override
	public void validate(Annotation annotation, Object v) {
		Range anno = (Range) annotation;
		if (v.getClass() == String.class) {
			int length = ((String) v).length();
			if (length < anno.min() || length > anno.max())
				throw new ValidateException(anno.value());
		} else {
			double value = ((Number) v).doubleValue();
			if (value < anno.min() || value > anno.max())
				throw new ValidateException(anno.value());
		}
	}
}
